<template>
    <div>
        <nav-popup title="新增保养记录"></nav-popup>

        <div style="padding: 10px 10px 0 10px;">
            <van-button type="info" round block @click="openPopup('week')">新增周保养</van-button>
        </div>

        <div style="padding: 10px 10px 0 10px;">
            <van-button type="info" round block @click="openPopup('month')">新增月保养</van-button>
        </div>

        <div style="padding: 10px 10px 0 10px;">
            <van-button type="info" round block @click="openPopup('quarter')">新增季保养</van-button>
        </div>

        <div style="padding: 10px 10px 0 10px;">
            <van-button type="info" round block @click="openPopup('year')">新增年保养</van-button>
        </div>

        <!-- 保养弹窗 -->
        <van-popup round v-model="popupVisible" class="custom-popup">
            <van-form @submit="onSubmit">
                <h3 class="popup-title">{{ popupTitle }}</h3>

                <!-- 保养时间 -->
                <van-field v-model="formModel.mainteDate" name="mainteDate" label="保养时间" placeholder="请选择保养时间" readonly
                    @click="showDatePicker = true" required :rules="[{ required: true, message: '请选择保养时间' }]" />

                <van-field v-model="formModel.headSN" name="headSN" label="headSN" required placeholder="headSN"
                    ref="headSN" :rules="[{ required: true, message: '请扫描 headSN' }]" />

                <van-field v-model="formModel.mainteEmpNo" name="mainteEmpNo" label="员工编号" required
                    placeholder="请输入员工编号" ref="mainteEmpNo" :rules="[{ required: true, message: '请填写员工编号' }]" />


                <van-field v-model="formModel.mainteEmpName" name="mainteEmpName" label="员工姓名" placeholder="请输入员工姓名" />

                <van-field v-model="formModel.mainteMark" name="mainteMark" label="备注信息" placeholder="请输入备注信息"
                    type="textarea" rows="2" />

                <div style="margin: 0 10px 0 10px;">
                    <van-button round block type="info" native-type="submit">提交</van-button>
                </div>
            </van-form>
        </van-popup>

        <!-- 保养日期弹框 -->
        <van-popup v-model="showDatePicker" round position="bottom" :style="{ height: '30%' }">
            <van-datetime-picker v-model="tempDate" type="date" title="选择日期" v-show="showDatePicker"
                @confirm="confirmDate" @cancel="showDatePicker = false" />
        </van-popup>
    </div>
</template>

<script>
import dayjs from "dayjs";
import NavPopup from "./NavPopup.vue";
import { Toast } from "vant";
import { AddMaintainRecord } from "@/network/headMaintain";

export default {
    name: "MaintainPage",
    components: { NavPopup },
    data() {
        return {
            popupVisible: false,
            showDatePicker: false,
            tempDate: new Date(),
            popupTitle: "",
            scanCount: 0,
            lastEmpNo: "",
            scanBuffer: "",
            formModel: {
                mainteType: "",
                headSN: "",
                mainteDate: "",
                mainteEmpNo: "",
                mainteEmpName: "",
                mainteMark: "",
            },
        };
    },
    mounted() {
        // 使用延时判断是否扫码结束
        window.addEventListener("keydown", this.handleScan);
    },
    destroyed() {
        window.removeEventListener("keydown", this.handleScan);
    },
    methods: {
        // 处理扫码枪输入
        handleScan(e) {
            if (e.key === "Enter") {
                const code = this.scanBuffer.trim();
                if (!code) return;

                this.scanCount++;

                if (this.scanCount === 1) {
                    // 第一次扫码：填写 headSN
                    this.formModel.headSN = code;
                    console.log("第一次扫描", code);

                    Toast.success("已填写 headSN");

                    // 自动聚焦到员工编号
                    this.$nextTick(() => {
                        this.$refs.mainteEmpNo.focus();
                    });

                } else if (this.scanCount === 2) {
                    // 第二次扫码：填写员工编号
                    this.formModel.mainteEmpNo = code;
                    this.lastEmpNo = code;

                    Toast.success("已填写员工编号");

                    // 自动失去焦点
                    this.$nextTick(() => {
                        this.$refs.mainteEmpNo.blur();
                    });

                } else if (this.scanCount === 3) {
                    // 第三次扫码：自动提交
                    if (code === this.lastEmpNo) {
                        this.autoSubmit();
                    } else {
                        Toast.fail("第三次扫码与员工编号不一致，请重新扫描");
                        this.scanCount--;
                    }
                }

                this.scanBuffer = "";
            } else {
                this.scanBuffer += e.key;
            }
        },


        // 自动提交
        async autoSubmit() {
            try {
                await AddMaintainRecord(this.formModel);
                Toast.success("自动提交成功");
                this.resetForm();
            } catch (error) {
                Toast.fail("提交失败，请重试");
                console.error(error);
            }
        },

        // 手动提交
        async manualSubmit() {
            try {
                await AddMaintainRecord(this.formModel);
                Toast.success("提交成功");
                this.resetForm();
            } catch (error) {
                Toast.fail("提交失败，请重试");
                console.error(error);
            }
        },

        openPopup(mode) {
            this.popupTitle = `新增${this.getModeTitle(mode)}保养`;
            this.popupVisible = true;
            this.resetForm();
            this.formModel.mainteType = mode;
            this.formModel.mainteDate = dayjs().format("YYYY-MM-DD");
        },
        getModeTitle(mode) {
            switch (mode) {
                case "week":
                    return "周";
                case "month":
                    return "月";
                case "quarter":
                    return "季";
                case "year":
                    return "年";
                default:
                    return "";
            }
        },
        resetForm() {
            this.formModel = {
                mainteType: "",
                headSN: "",
                mainteDate: dayjs().format("YYYY-MM-DD"),
                mainteEmpNo: "",
                mainteEmpName: "",
                mainteMark: "",
            };
            this.scanCount = 0;
            this.scanBuffer = "";
        },
        async onSubmit() {
            await this.manualSubmit();
        },
        confirmDate(date) {
            this.formModel.mainteDate = dayjs(date).format("YYYY-MM-DD");
            this.showDatePicker = false;
        },
    },
};
</script>

<style scoped>
.custom-popup {
    height: 63%;
    width: 75%;
}

.popup-title {
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
}
</style>
